package product

import (
	"context"
	"errors"
	"group-buy/group_buy/internal/models"

	"group-buy/group_buy/internal/svc"
	"group-buy/group_buy/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type SaveLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewSaveLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SaveLogic {
	return &SaveLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *SaveLogic) Save(req *types.Product) (resp *types.Product, err error) {
	m := &models.Product{
		Id:             req.Id,
		Name:           req.Name,
		Price:          req.Price,
		Unit:           req.Unit,
		Cover:          req.Cover,
		Detail:         req.Detail,
		BusinessId:     req.BusinessId,
		Sort:           req.Sort,
		WriteOff:       req.WriteOff,
		Status:         req.Status,
		WriteOffUserId: req.WriteOffUserId,
	}
	if m.Id == 0 && m.Status == 2 {
		return nil, errors.New("新增商品不能直接上架")
	}
	if m.Status == 2 {
		division := &models.ProductDivision{ProductId: m.Id}
		exist, err := l.svcCtx.Engine.Exist(division)
		if err != nil {
			return nil, err
		}
		if !exist {
			return nil, errors.New("请先完成分账配置")
		}
	}

	if m.Id > 0 {
		_, err = l.svcCtx.Engine.ID(m.Id).Update(m)
		if err != nil {
			return nil, err
		}
	} else {
		_, err = l.svcCtx.Engine.Insert(m)
		if err != nil {
			return nil, err
		}
	}
	req.Id = m.Id

	return req, nil
}
